#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
文件组织选项卡 - 负责文件整理功能的GUI界面
"""

import os
import threading
import tkinter as tk
from tkinter import ttk, filedialog, messagebox
from pathlib import Path

from core import organizer

class OrganizerTab(ttk.Frame):
    """文件组织选项卡"""
    
    def __init__(self, parent):
        super().__init__(parent)
        
        # 创建变量
        self.source_dir_var = tk.StringVar()
        self.target_dir_var = tk.StringVar()
        self.organize_type_var = tk.StringVar(value="type")
        self.date_format_var = tk.StringVar(value="年份/月份")
        self.use_modified_var = tk.BooleanVar(value=False)
        self.regex_patterns_var = tk.StringVar()
        
        # 创建界面元素
        self.create_widgets()
        
        # 绑定事件
        self.organize_type_var.trace("w", self.on_organize_type_changed)
        
        # 初始状态设置
        self.on_organize_type_changed()
    
    def create_widgets(self):
        """创建界面元素"""
        # 创建主框架
        main_frame = ttk.Frame(self)
        main_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
        
        # 源目录选择
        source_frame = ttk.LabelFrame(main_frame, text="源目录")
        source_frame.pack(fill=tk.X, pady=5)
        
        ttk.Entry(source_frame, textvariable=self.source_dir_var).pack(side=tk.LEFT, fill=tk.X, expand=True, padx=5, pady=5)
        ttk.Button(source_frame, text="浏览...", command=self.browse_source_dir).pack(side=tk.LEFT, padx=5, pady=5)
        
        # 目标目录选择（可选）
        target_frame = ttk.LabelFrame(main_frame, text="目标目录（可选，默认在源目录中创建子目录）")
        target_frame.pack(fill=tk.X, pady=5)
        
        ttk.Entry(target_frame, textvariable=self.target_dir_var).pack(side=tk.LEFT, fill=tk.X, expand=True, padx=5, pady=5)
        ttk.Button(target_frame, text="浏览...", command=self.browse_target_dir).pack(side=tk.LEFT, padx=5, pady=5)
        
        # 整理类型选择
        organize_type_frame = ttk.LabelFrame(main_frame, text="整理类型")
        organize_type_frame.pack(fill=tk.X, pady=5)
        
        ttk.Radiobutton(organize_type_frame, text="按文件类型整理", variable=self.organize_type_var, value="type").pack(anchor=tk.W, padx=5, pady=2)
        ttk.Radiobutton(organize_type_frame, text="按日期整理", variable=self.organize_type_var, value="date").pack(anchor=tk.W, padx=5, pady=2)
        ttk.Radiobutton(organize_type_frame, text="按文件大小整理", variable=self.organize_type_var, value="size").pack(anchor=tk.W, padx=5, pady=2)
        ttk.Radiobutton(organize_type_frame, text="按正则表达式整理", variable=self.organize_type_var, value="regex").pack(anchor=tk.W, padx=5, pady=2)
        
        # 日期选项（按日期整理时显示）
        self.date_options_frame = ttk.LabelFrame(main_frame, text="日期选项")
        
        date_format_frame = ttk.Frame(self.date_options_frame)
        date_format_frame.pack(fill=tk.X, padx=5, pady=5)
        
        ttk.Label(date_format_frame, text="日期格式:").pack(side=tk.LEFT, padx=5)
        ttk.Radiobutton(date_format_frame, text="年份", variable=self.date_format_var, value="年份").pack(side=tk.LEFT, padx=5)
        ttk.Radiobutton(date_format_frame, text="年份/月份", variable=self.date_format_var, value="年份/月份").pack(side=tk.LEFT, padx=5)
        ttk.Radiobutton(date_format_frame, text="年份/月份/日期", variable=self.date_format_var, value="年份/月份/日期").pack(side=tk.LEFT, padx=5)
        
        ttk.Checkbutton(self.date_options_frame, text="使用修改日期（默认使用创建日期）", variable=self.use_modified_var).pack(anchor=tk.W, padx=5, pady=5)
        
        # 正则表达式选项（按正则表达式整理时显示）
        self.regex_options_frame = ttk.LabelFrame(main_frame, text="正则表达式选项")
        
        ttk.Label(self.regex_options_frame, text="格式: 类别1:正则表达式1, 类别2:正则表达式2, ...").pack(anchor=tk.W, padx=5, pady=2)
        ttk.Entry(self.regex_options_frame, textvariable=self.regex_patterns_var).pack(fill=tk.X, padx=5, pady=5)
        ttk.Label(self.regex_options_frame, text="示例: 图片:.*\.jpg$, 文档:.*\.pdf$").pack(anchor=tk.W, padx=5, pady=2)
        
        # 执行按钮和进度区
        action_frame = ttk.Frame(main_frame)
        action_frame.pack(fill=tk.X, pady=10)
        
        self.progress_var = tk.StringVar(value="")
        ttk.Label(action_frame, textvariable=self.progress_var).pack(side=tk.LEFT, fill=tk.X, expand=True, padx=5)
        ttk.Button(action_frame, text="执行整理", command=self.organize_files).pack(side=tk.RIGHT, padx=5)
        
        # 结果显示区域
        results_frame = ttk.LabelFrame(main_frame, text="整理结果")
        results_frame.pack(fill=tk.BOTH, expand=True, pady=5)
        
        self.results_text = tk.Text(results_frame, wrap=tk.WORD, height=10)
        self.results_text.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
        
        scrollbar = ttk.Scrollbar(self.results_text, command=self.results_text.yview)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        self.results_text.config(yscrollcommand=scrollbar.set)
        self.results_text.config(state=tk.DISABLED)
    
    def on_organize_type_changed(self, *args):
        """整理类型变化时的处理"""
        organize_type = self.organize_type_var.get()
        
        # 隐藏所有选项
        if hasattr(self, 'date_options_frame'):
            self.date_options_frame.pack_forget()
        if hasattr(self, 'regex_options_frame'):
            self.regex_options_frame.pack_forget()
        
        # 根据所选类型显示相应选项
        if organize_type == "date":
            self.date_options_frame.pack(fill=tk.X, pady=5)
        elif organize_type == "regex":
            self.regex_options_frame.pack(fill=tk.X, pady=5)
    
    def browse_source_dir(self):
        """浏览选择源目录"""
        directory = filedialog.askdirectory(title="选择源目录")
        if directory:
            self.source_dir_var.set(directory)
    
    def browse_target_dir(self):
        """浏览选择目标目录"""
        directory = filedialog.askdirectory(title="选择目标目录")
        if directory:
            self.target_dir_var.set(directory)
    
    def organize_files(self):
        """执行文件整理"""
        # 获取参数
        source_dir = self.source_dir_var.get()
        target_dir = self.target_dir_var.get() or None
        organize_type = self.organize_type_var.get()
        
        # 验证源目录
        if not source_dir:
            messagebox.showerror("错误", "请选择源目录")
            return
        
        if not os.path.exists(source_dir) or not os.path.isdir(source_dir):
            messagebox.showerror("错误", f"源目录不存在或不是一个有效的目录: {source_dir}")
            return
        
        # 验证目标目录
        if target_dir and not os.path.exists(target_dir):
            try:
                os.makedirs(target_dir)
            except Exception as e:
                messagebox.showerror("错误", f"无法创建目标目录: {str(e)}")
                return
        
        # 验证正则表达式
        patterns = {}
        if organize_type == "regex":
            regex_patterns = self.regex_patterns_var.get()
            if not regex_patterns:
                messagebox.showerror("错误", "请输入正则表达式模式")
                return
            
            try:
                # 解析正则表达式模式
                for pattern_str in regex_patterns.split(','):
                    pattern_str = pattern_str.strip()
                    if not pattern_str:
                        continue
                    
                    if ":" not in pattern_str:
                        messagebox.showerror("错误", f"模式格式不正确: {pattern_str}\n正确格式: 类别名:正则表达式")
                        return
                    
                    category, regex = pattern_str.split(":", 1)
                    patterns[category.strip()] = regex.strip()
            except Exception as e:
                messagebox.showerror("错误", f"解析正则表达式时出错: {str(e)}")
                return
        
        # 清空结果区域
        self.results_text.config(state=tk.NORMAL)
        self.results_text.delete(1.0, tk.END)
        self.results_text.config(state=tk.DISABLED)
        
        # 更新进度显示
        self.progress_var.set("正在整理文件...")
        
        # 在线程中执行文件整理
        threading.Thread(target=self._organize_files_thread, args=(
            source_dir, target_dir, organize_type, patterns
        )).start()
    
    def _organize_files_thread(self, source_dir, target_dir, organize_type, patterns):
        """在线程中执行文件整理"""
        try:
            stats = {}
            
            # 执行对应的整理方法
            if organize_type == "type":
                stats = organizer.organize_by_type(source_dir, target_dir)
            
            elif organize_type == "date":
                date_format = self.date_format_var.get()
                use_modified = self.use_modified_var.get()
                stats = organizer.organize_by_date(source_dir, target_dir, date_format, use_modified)
            
            elif organize_type == "size":
                stats = organizer.organize_by_size(source_dir, target_dir)
            
            elif organize_type == "regex":
                stats = organizer.organize_by_regex(source_dir, target_dir, patterns)
            
            # 更新结果显示
            self.show_results(stats)
            
            # 更新进度显示
            self.progress_var.set("文件整理完成")
            
        except Exception as e:
            # 更新进度显示
            self.progress_var.set("整理文件时出错")
            
            # 显示错误消息
            messagebox.showerror("错误", f"整理文件时出错: {str(e)}")
    
    def show_results(self, stats):
        """显示整理结果"""
        if not stats:
            return
        
        # 更新结果区域
        self.results_text.config(state=tk.NORMAL)
        self.results_text.delete(1.0, tk.END)
        
        self.results_text.insert(tk.END, "整理结果:\n\n")
        
        for category, count in sorted(stats.items()):
            if count > 0:
                self.results_text.insert(tk.END, f"{category}: {count} 个文件\n")
        
        self.results_text.config(state=tk.DISABLED) 